package com.wecommodule.bpm.ext.framework.config.support;

import okhttp3.Call;
import okhttp3.EventListener;
import okhttp3.Protocol;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;

/**
 * 用于记录连接失败和调用失败的EventListener。
 */
public class FailureEventListener extends EventListener {

    /**
     * This instance logger.
     */
    @NotNull
    private final Logger logger;

    /**
     * Builds an event listener instance.
     */
    public FailureEventListener() {
        logger = LoggerFactory.getLogger(FailureEventListener.class);
    }

    @Override
    public void connectFailed(@NotNull Call call, @NotNull InetSocketAddress targetAddress, @NotNull Proxy proxy,
                              @Nullable Protocol protocol, @NotNull IOException ex) {
        String message = new StringBuilder()
                .append("发起请求连接失败!  ")
                .append("目标地址：").append(targetAddress).append("&")
                .append("代理：").append(proxy).append("&")
                .append("协议：").append(protocol).append("&").toString();
        // log connection failure.
        logger.error(message, ex);
    }

    @Override
    public void callFailed(@NotNull Call call, @NotNull IOException ex) {
        String message = new StringBuilder()
                .append("发起请求调用失败!  ")
                .append("目标地址：").append(call.request().url()).append("&")
                .append("请求方式：").append(call.request().method()).append("&")
                .append("请求头：").append(call.request().headers()).append("&")
                .append("是否HTTPS：").append(call.request().isHttps()).append("&").toString();
        logger.error(message, ex);
    }


}
